from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from read_book.wechat import robot
from read_book import wechat
from user.models import *
import datetime, time
import json
import requests
import base64
from user import base


def index(request):
    url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2fab5d8fc63cdcee&redirect_uri=http://www.unihyj.cn/user/get_openid&response_type=code&scope=snsapi_base&state=%d#wechat_redirect' % int(time.time())
    return HttpResponseRedirect(url)

def borrowing(request):
    user = User.objects.get(id=request.session.get('user_id'))
    booklist = list(Borrow.objects.filter(user=user, status='1'))
    for book in booklist:
        book.remain_time = 30 - (datetime.datetime.now() - book.borrow_time).days
    return_data = {'booklist': booklist, 'user_id': request.session.get('user_id')}
    return render(request, 'user/borrowing.html', return_data)

def all_borrow(request):
    user = User.objects.get(id=request.session.get('user_id'))
    booklist = list(Borrow.objects.filter(user=user))
    booklist.sort(key=lambda x:x.status)
    for book in booklist:
        if book.status == '1':
            book.return_time += datetime.timedelta(days=30)
    return_data = {'booklist': booklist}
    return render(request, 'user/all_borrow.html', return_data)

def bookbill(request):
    user = User.objects.get(id=request.session.get('user_id'))
    booklist = BookBill.objects.filter(user=user)
    return_data = {'booklist': booklist, 'user_id': request.session.get('user_id')}
    return_data.update(wechat.jsapi(request.build_absolute_uri()))
    return render(request, 'user/bookbill.html', return_data)

def add_bookbill(request):
    try:
        result = request.GET.get('result')
        result = base.decryption(result.encode('utf-8'))
        book_info = json.loads(result)
        book = Book.objects.get(id=book_info['id'])
        if book_info['name'] == book.name:
            if book.remain_count > 0:
                user = User.objects.get(id=request.session.get('user_id'))
                bill = BookBill.objects.create(user=user, book=book)
                return_data = {
                    'status': 1,             # 添加成功，返回状态1
                    'id': book.id,
                    'cover': book.cover.url,
                    'name': book.name,
                    'author': book.author,
                    'remain_count': book.remain_count,
                    'bookbill_id': bill.id,
                }
                return HttpResponse(json.dumps(return_data))
            else:
                return HttpResponse(json.dumps({'status': 3}))  # 添加失败,库存不足
        else:
            return HttpResponse(json.dumps({'status': 4}))  # 添加失败,二维码信息与数据库信息不一致，二维码过期
    except:
        return HttpResponse(json.dumps({'status': 2}))

def del_bookbill(request, bill_id):
    try:
        bookbill = BookBill.objects.filter(id=bill_id)
        if len(bookbill)>0:
            bookbill[0].delete()
        return HttpResponse(json.dumps({'status': 1}))   # 删除成功，返回状态1
    except:
        return HttpResponse(json.dumps({'status': 2}))   # 删除失败，返回状态2

def borrow(request):
    user = User.objects.get(id= request.POST.get('user_id'))
    res_bookbill = BookBill.objects.filter(user=user)
    if (res_bookbill):
        for bookbill in res_bookbill:
            book = bookbill.book
            if book.remain_count > 0:
                Borrow.objects.create(user=user, book=book, status='1')  # 添加至借书表
                book.remain_count -= 1  # 此书库存-1
                book.save()
                bookbill.delete()
                return HttpResponse(json.dumps({'status': 1}))  # 借书成功
            else:
                return HttpResponse(json.dumps({'status': 3}))  # 借书失败,库存不足
    else:
        return HttpResponse(json.dumps({'status': 2}))  # 失败：借书单无书

def return_book(request):
    user = User.objects.get(id= request.POST.get('user_id'))
    books_id = request.POST.get('books_id').split(',')
    for book_id in map(int, books_id):
        book = Book.objects.get(id=book_id)
        b = Borrow.objects.get(user=user, book=book, status='1')
        b.return_time = datetime.datetime.now()    # 设置还书时间
        b.status = '2'                             # 设置状态为已还
        book.remain_count += 1                     # 书剩余+1
        book.save()
        b.save()
    return HttpResponse(json.dumps({'status': 1}))

def get_openid(request):
    # 引导url: https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2fab5d8fc63cdcee&redirect_uri=http://www.unihyj.cn/user/get_openid&response_type=code&scope=snsapi_base&state=userindex#wechat_redirect
    code = request.GET.get('code')
    url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={APPID}&secret={SECRET}&code={CODE}&grant_type=authorization_code".format(
        APPID = robot.config['APP_ID'],
        SECRET = robot.config['APP_SECRET'],
        CODE = code,
    )
    r = requests.get(url)
    data = json.loads(r.text)
    #return HttpResponse(r.text)
    openid = data.get('openid')
    if not openid:
        return HttpResponse(r.text)
    # 返回用户首页-
    user = User.objects.filter(openid=openid)
    if len(user)>0:
        user = user[0]
    else:
        user = wechat.sign_user(openid)
    request.session['user_id'] = user.id
    return_data = {'userinfo': user}
    if user.operation == '1':
        return_data.update(wechat.jsapi(request.build_absolute_uri()))
    return render(request, 'user/index.html', return_data)

def get_qrcode(request):
    ticket = wechat.qrcode()
    qrcode_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket
    return HttpResponseRedirect(qrcode_url)

def borrow_qrcode(request, user_id):
    book_info = {
        "oper": "borrow",
        "userid": user_id,
        "time": time.time()
    }
    book_info = json.dumps(book_info)
    book_info = base.encryption(book_info)
    return base.make_qrcode(book_info)

def return_qrcode(request, user_id):
    book_info = {
        "oper": "return",
        "userid": user_id,
        "time": time.time()
    }
    book_info = json.dumps(book_info)
    book_info = base.encryption(book_info)
    return base.make_qrcode(book_info)


def operation(request):
    result = request.GET.get('result')
    result = base.decryption(result.encode('utf-8'))
    result = json.loads(result)
    return_data = {}
    if result['oper'] == "borrow":       # 借书
        user = User.objects.get(id=result['userid'])
        bookbills = BookBill.objects.filter(user=user)
        return_data = {'userinfo': user, 'booklist': bookbills, 'book_count': len(bookbills), 'oper': "borrow"}     # 返回确认页，操作为借书
    elif result['oper'] == 'return':    # 还书
        user = User.objects.get(id=result['userid'])      # 获取所有在读图书
        bookbills = Borrow.objects.filter(user=user, status='1')
        return_data = {'userinfo': user, 'booklist': bookbills, 'book_count': len(bookbills), 'oper': "return"}  # 返回确认页，操作为还书
    return render(request, 'user/operation.html', return_data)

